import requests

# r=requests.get('http://www.baidu.com')
# r.encoding='utf-8'
# https://tieba.baidu.com/f?kw=奥特曼&pn=0
# https://tieba.baidu.com/f?kw=奥特曼&pn=50
# https://tieba.baidu.com/f?kw=奥特曼&pn=150
class Tieba_spider(object):
    def __init__(self,text):
        self.text=text
        self.url='https://tieba.baidu.com/f?kw='+text+'&pn={}'
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36"}
    def get_url_list(self):
        """生成url"""
        list_url=[self.url.format(i * 50) for i in range(5)]
        return  list_url

    def get_data_fromurl(self,url):
        """"从服务器获取数据,并解码返回"""
        r = requests.get(url, headers=self.headers)
        return r.content.decode()

    def save_html(self,html_str,num):
        file_name = "贴吧" + text + '第{}页'.format(num) + '.html'
        with open(file_name, 'w', encoding='utf-8') as f:
            f.write(html_str)


    def run(self):
        """确定生成url生成url列表"""
        list_url=self.get_url_list()
        for item_url in list_url:
            html_str=self.get_data_fromurl(item_url)


            #保存
            self.save_html(html_str,list_url.index(item_url)+1)
if __name__=='__main__':
    text=input('请输入贴吧名字:')
    spider=Tieba_spider(text)
    spider.run()


















# url = 'https://tieba.baidu.com/f?kw={}&pn={}'
# text = input('请输入贴吧名:')
# list_url = [url.format(text, i * 50) for i in range(5)]
# print(list_url)
# headers = {
#     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36"}
#
# for item_url in list_url:
#     r = requests.get(item_url, headers=headers)
#
#     file_name = "贴吧" + text + '第{}页'.format(list_url.index(item_url) + 1) + '.html'
#     with open(file_name, 'w',encoding='utf-8') as f:
#         f.write(r.content.decode())

# params={"wd" : text}
# # r=requests.get(url.format(text),headers=headers)
# r=requests.get(url,headers=headers,params=params)

# print(r.text)

# print(r.content.decode())
# print(r.request.headers)
# print(r.request.url)


# image_url='https://s3.bmp.ovh/imgs/2021/08/464a3c6600a0fd48.jpg'
# response=requests.get(image_url)
# print(response.content)
# with open('照片.jpg','wb') as f:
#     f.write(response.content)
